package com.ruoyi.web.controller.api;
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.system.domain.BusinessCard;
import com.ruoyi.system.domain.LoginInfo;
import com.ruoyi.system.domain.dUser;
import com.ruoyi.system.service.IBusinessCardService;
import com.ruoyi.system.service.ILoginInfoService;
import com.ruoyi.system.service.IdUserService;
import com.ruoyi.web.domian.sqlReturn;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import org.apache.commons.codec.binary.Base64;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.web.core.config.sqlYz.LoginRequired;
import com.ruoyi.web.controller.token.sqlToken;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Controller
@RequestMapping("/sql_api")
public class sqlUserLoginContriller extends BaseController {
    @Autowired
    private IdUserService dUserService;

    @Autowired
    private IBusinessCardService IBusinessCardService;

    @Autowired
    private ILoginInfoService ILoginInfoService;


//    登录操作
    @PostMapping("/login")
    @ResponseBody
    public sqlReturn login(HttpServletRequest req , String phone,String bcd_id,String userId){
        System.out.println(bcd_id+"\t");
        try {
//           打印请求的
            String ipAddress = req.getRemoteAddr() +"||"+ req.getMethod();
            String token = sqlToken.generateToken(phone);
            dUser dUser=new dUser();
            dUser.setUserPhone(phone);
//            查找用户
            List<dUser> list=dUserService.selectdUserList(dUser);
            if(list.size() == 0){
                return new sqlReturn(null,"用户不存在",400);
            }
            dUser.setUserId(list.get(0).getUserId());
            dUser.setUserToken(token);
            dUserService.updatedUser(dUser);
            HashMap<String,Object> map=new HashMap<>();
            map.put("token",token);
            map.put("user",list);
            BusinessCard businessCard = new BusinessCard();
            System.out.println(list.get(0).getUserId()+"+++++++++++++");
            System.out.println(bcd_id+"+++++++++++++");

            if(bcd_id==""){
                businessCard.setUserId(list.get(0).getUserId());
            }else{
                businessCard.setBcId(Long.parseLong(bcd_id));
                businessCard.setUserId(Long.parseLong(userId));
            }
            System.out.println(businessCard+"\t");
//            查找对应的电子名片
            List<BusinessCard> bcd  =IBusinessCardService.selectBusinessCardList(businessCard);
            System.out.println(bcd+"=====");
            if(bcd.size()==0){
                map.put("bcd",null);
            }else{
                map.put("bcd",bcd);
            }
//            登录记录
            LoginInfo LoginInfo= new LoginInfo();
            LoginInfo.setToken(token);
            LoginInfo.setLiInsdate(new Date());
            LoginInfo.setLiIp(ipAddress);
            LoginInfo.setUsreId(list.get(0).getUserId());
            int i =  ILoginInfoService.insertLoginInfo(LoginInfo);
            sqlReturn ret=new sqlReturn(map ,"登陆成功",200);
            return ret;
        } catch (AuthenticationException e){
            return new sqlReturn(null,"网络异常",400);
        }
    }


    public static String decryptPhoneNumber(String base64SessionKey, String encryptedData, String iv) throws Exception {
        byte[] encData = Base64.decodeBase64(encryptedData);
        byte[] keyBytes = Base64.decodeBase64(base64SessionKey); // 修改这里，直接解码Base64格式的session_key
        byte[] ivBytes = Base64.decodeBase64(iv);

        Key keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

        byte[] result = cipher.doFinal(encData);
        return new String(result, StandardCharsets.UTF_8);
    }


//   获取 access_token  微信
    @PostMapping("/get_AccessToken")
    @ResponseBody
    public sqlReturn get_AccessToken(String appid,String secret,String code,String iv,String encryptedData){
        try {
//            获取 AccessToken
            RestTemplate restTemplate = new RestTemplate();
            String url = "https://api.weixin.qq.com/sns/jscode2session?js_code=" + code
                    + "&appid=" + appid
                    + "&secret=" + secret;
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response.getBody());
//            用iv encryptedData jsonNode.get("session_key")  解密  手机号
            String data = decryptPhoneNumber(jsonNode.get("session_key").asText(), encryptedData, iv);
//            提取 phoneNumber 的 phoneNumber数据
            JSONObject jsonObject = new JSONObject(data);
            String phoneNumber = jsonObject.getString("phoneNumber");
            HashMap<String,Object> ret=new HashMap<>();
            ret.put("phoneNumber",phoneNumber);


            return new sqlReturn(ret,"获取成功",200);
        }catch(AuthenticationException e){
            return new sqlReturn(null,"获取失败",500);
        } catch (JsonMappingException e) {
            throw new RuntimeException(e);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


//    通过token获取手机号
    @PostMapping("/getphone_token")
    @ResponseBody
    public sqlReturn getphone_token(String token){
        try {
            dUser dUser=new dUser();
            dUser.setUserToken(token);
            List<dUser> list=dUserService.selectdUserList(dUser);
            if(list.size() == 0){
                return new sqlReturn(null,"用户不存在",400);
            }
            HashMap<String,Object> ret=new HashMap<>();
            ret.put("userPhone",list.get(0).getUserPhone());
            return new sqlReturn(ret,"登陆成功",200);
        }catch (AuthenticationException e){
            return new sqlReturn(null,"网络异常",500);
        }
    }
}
